package com.programmercarl.string;

import java.util.Arrays;
import java.util.Objects;

/**
 * https://leetcode.cn/problems/reverse-words-in-a-string/
 *
 * @author yulongtian
 * @create 2024-12-15 12:19
 */
public class Test04 {
    public static void main(String[] args) {
        String s = "  hello world  ";
        String[] split = s.split(" ");
        System.out.println(Arrays.toString(split));
    }

    public String reverseWords(String s) {
        String[] split = s.split(" ");
        int i = 0, j = split.length - 1;
        while (i < j) {
            if (Objects.equals(split[i], "")) {
                i++;
                continue;
            }
            if (Objects.equals(split[j], "")) {
                j--;
                continue;
            }
            String temp = split[i];
            split[i] = split[j];
            split[j] = temp;
            i++;
            j--;
        }
        StringBuilder builder = new StringBuilder();
        for (int k = 0; k < split.length; k++) {
            String ss = split[k];
            if (ss.isEmpty()) {
                continue;
            }
            if (k == split.length - 1) {
                builder.append(ss);
            } else {
                builder.append(ss).append(" ");
            }
        }

        return builder.toString();
    }
}
